"""
操作日志管理API
"""
from fastapi import APIRouter, HTTPException, status, Depends
from typing import Optional
from models.m import OperationLog, AdminUser
from schemas.admin_schemas import ResponseModel
from utils.auth_middleware import get_current_user
from tortoise.expressions import Q


log_router = APIRouter(prefix="/admin/logs", tags=["操作日志"])


@log_router.get("", response_model=ResponseModel, summary="获取操作日志列表")
async def get_operation_logs(
    page: int = 1,
    page_size: int = 20,
    user_id: Optional[int] = None,
    action: Optional[str] = None,
    module: Optional[str] = None,
    status: Optional[int] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取操作日志列表（支持多条件筛选）
    """
    query = OperationLog.all()
    
    # 条件筛选
    if user_id is not None:
        query = query.filter(user_id=user_id)
    
    if action:
        query = query.filter(action__icontains=action)
    
    if module:
        query = query.filter(module__icontains=module)
    
    if status is not None:
        query = query.filter(status=status)
    
    if start_date:
        query = query.filter(create_time__gte=start_date)
    
    if end_date:
        query = query.filter(create_time__lte=end_date)
    
    # 统计总数
    total = await query.count()
    
    # 分页查询
    offset = (page - 1) * page_size
    logs = await query.offset(offset).limit(page_size).order_by('-id').prefetch_related('user')
    
    # 组装响应
    items = []
    for log in logs:
        items.append({
            "id": log.id,
            "user_id": log.user_id,
            "username": log.user.username if log.user else None,
            "action": log.action,
            "module": log.module,
            "description": log.description,
            "ip": log.ip,
            "user_agent": log.user_agent,
            "request_data": log.request_data,
            "response_data": log.response_data,
            "status": log.status,
            "error_msg": log.error_msg,
            "create_time": log.create_time.isoformat(),
        })
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "total": total,
            "page": page,
            "page_size": page_size,
            "items": items
        }
    }


@log_router.get("/{log_id}", response_model=ResponseModel, summary="获取日志详情")
async def get_log_detail(
    log_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取操作日志详情
    """
    log = await OperationLog.get_or_none(id=log_id).prefetch_related('user')
    
    if not log:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="日志不存在")
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "id": log.id,
            "user_id": log.user_id,
            "username": log.user.username if log.user else None,
            "action": log.action,
            "module": log.module,
            "description": log.description,
            "ip": log.ip,
            "user_agent": log.user_agent,
            "request_data": log.request_data,
            "response_data": log.response_data,
            "status": log.status,
            "error_msg": log.error_msg,
            "create_time": log.create_time.isoformat(),
        }
    }


@log_router.get("/stats/summary", response_model=ResponseModel, summary="获取日志统计")
async def get_log_stats(current_user: AdminUser = Depends(get_current_user)):
    """
    获取操作日志统计信息
    """
    from tortoise import connections
    
    conn = connections.get("default")
    
    # 按模块统计
    module_stats_sql = """
        SELECT module, COUNT(*) as count
        FROM admin_operation_logs
        GROUP BY module
        ORDER BY count DESC
        LIMIT 10
    """
    module_stats = await conn.execute_query_dict(module_stats_sql)
    
    # 按操作统计
    action_stats_sql = """
        SELECT action, COUNT(*) as count
        FROM admin_operation_logs
        GROUP BY action
        ORDER BY count DESC
        LIMIT 10
    """
    action_stats = await conn.execute_query_dict(action_stats_sql)
    
    # 按用户统计
    user_stats_sql = """
        SELECT u.username, COUNT(*) as count
        FROM admin_operation_logs l
        LEFT JOIN admin_users u ON l.user_id = u.id
        GROUP BY l.user_id
        ORDER BY count DESC
        LIMIT 10
    """
    user_stats = await conn.execute_query_dict(user_stats_sql)
    
    # 今日操作数
    today_count_sql = """
        SELECT COUNT(*) as count
        FROM admin_operation_logs
        WHERE DATE(create_time) = CURDATE()
    """
    today_count = await conn.execute_query_dict(today_count_sql)
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "module_stats": module_stats,
            "action_stats": action_stats,
            "user_stats": user_stats,
            "today_count": today_count[0]['count'] if today_count else 0
        }
    }

